package org.example.first_demo.controler;

import org.example.first_demo.pojo.User;
import org.example.first_demo.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController // 声明这是一个 RESTful Controller，返回的数据会是 JSON 格式
@RequestMapping("/api/users") // 这个 Controller 下的所有接口路径都以 /api/users 开头
public class UserController {

    @Autowired
    private UserService userService;

    // 1. 获取所有用户 (GET /api/users)
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    // 2. 根据 ID 获取单个用户 (GET /api/users/{id})
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Integer id) {
        return userService.getUserById(id)
                .map(ResponseEntity::ok) // 如果找到，返回 200 OK 和用户信息
                .orElse(ResponseEntity.notFound().build()); // 如果没找到，返回 404 Not Found
    }

    // 3. 创建新用户 (POST /api/users)
    @PostMapping
    public User createUser(@RequestBody User user) {
        // @RequestBody 会将请求体中的 JSON 自动转换为 User 对象
        return userService.createUser(user);
    }

    // 4. 更新用户信息 (PUT /api/users/{id})
    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Integer id, @RequestBody User userDetails) {
        try {
            User updatedUser = userService.updateUser(id, userDetails);
            return ResponseEntity.ok(updatedUser);
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }

    // 5. 删除用户 (DELETE /api/users/{id})
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Integer id) {
        try {
            userService.deleteUser(id);
            return ResponseEntity.noContent().build(); // 删除成功，返回 204 No Content
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }
}